package com.lishem.top100._08tree;


import com.lishem.common.TreeNode;

import java.util.Stack;

/**
 * https://leetcode.cn/problems/kth-smallest-element-in-a-bst/description/
 * <p>
 * 给定一个二叉搜索树的根节点 root ，和一个整数 k ，
 * <p>
 * 请你设计一个算法查找其中第 k 个最小元素（从 1 开始计数）。
 */
public class _09LetCode230_二叉搜索树中第K小的元素 {

    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        int index = 1;
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                if (index == k) {
                    return root.val;
                }
                index++;
                root = root.right;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        _09LetCode230_二叉搜索树中第K小的元素 sol = new _09LetCode230_二叉搜索树中第K小的元素();

        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(1);
        root.left.right = new TreeNode(2);
        root.right = new TreeNode(4);
        System.out.println(sol.kthSmallest(root, 1));
    }
}
